package com.example.mytest327;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothAdapter;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import androidx.core.content.ContextCompat;

import android.Manifest;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;

import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.provider.Settings;
import android.util.Log;
import android.content.Intent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
//    private static final UUID MY_UUID = UUID.fromString("bef8d6c9-9c21-4c9e-b632-bd58c100"); //自己填写uuid
    private static final UUID SERVICE_UUID = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");

    //要找到对应设备去填写
    private static final UUID WRITE_UUID = UUID.fromString("0000fff2-0000-1000-8000-00805f9b34fb");
    private static final UUID NOTIFY_UUID = UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb");

    private List<String> macs = new ArrayList<>();

    private BluetoothAdapter bluetoothAdapter;
    private final static int REQUEST_ENABLE_BT = 1;
    private TextView myTextView;

    private ScrollView mScrollView;

    private static final int REQUEST_CODE_OPEN_GPS = 1;
    private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
//    private BluetoothListAdapter mAdapter;
//    private RecyclerView mRecyclerView;

    private ActivityResultLauncher<Intent> enableBtLauncher =
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                    result -> {
                        if (result.getResultCode() == RESULT_OK) {
                            // 用户已启用蓝牙
//                            startBluetoothDiscovery();
                        } else {
                            // 用户未启用蓝牙
                            // 处理其他情况
                        }
                    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mScrollView = findViewById(R.id.scroll_view);
        // 获取对 TextView 的引用
        myTextView = findViewById(R.id.textView);
//        mRecyclerView = findViewById(R.id.recycle_view);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

//        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//        mAdapter = new BluetoothListAdapter(new ArrayList<>(),this);
//        mRecyclerView.setAdapter(mAdapter);
        // 如果设备不支持蓝牙，则提示用户并退出应用程序
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "Device does not support Bluetooth", Toast.LENGTH_SHORT).show();
            finish();
            myTextView.setText("Device does not support Bluetooth!");
            return;
        }

        // 如果蓝牙未启用，则请求用户启用蓝牙
        if (!bluetoothAdapter.isEnabled()) {
//            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//            enableBtLauncher.launch(enableBtIntent);
            BleManager.getInstance().enableBluetooth();

        } else {
//            startBluetoothDiscovery();
//            connectToBluetoothDevice();
        }

    }

    private void scanBleDevice(){
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
//                .setServiceUuids(new UUID[]{SERVICE_UUID})  //只扫指定uuid蓝牙
                .setDeviceName(true, "OBDII")
                .setAutoConnect(false)
                .setScanTimeOut(10000)
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);
        BleManager.getInstance().enableLog(true)
                .setMaxConnectCount(5)
                .scan(new BleScanCallback() {
                    @Override
                    public void onScanFinished(List<BleDevice> scanResultList) {
                        addLog("扫描结束");
                    }

                    @Override
                    public void onScanStarted(boolean success) {
                        addLog("开始扫描");
                    }

                    @Override
                    public void onScanning(BleDevice bleDevice) {
                        addLog("扫描到设备:"+bleDevice.getMac());
                        BleManager.getInstance().cancelScan();
                        connect(bleDevice);
                    }
                });
    }


    private void connect(BleDevice device){
            addLog("connect:"+device.getName());
            String  mac = device.getMac();
            if(!macs.contains(mac)){
                BleManager.getInstance().connect(device, new BleGattCallback() {
                    @Override
                    public void onStartConnect() {
                        addLog("connecting:"+device.getName());
                    }

                    @Override
                    public void onConnectFail(BleDevice bleDevice, BleException exception) {
                        Log.i(TAG, "connect fail: "+device.getName());
                        addLog("onConnectFail " + device.getMac());
                    }

                    @Override
                    public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                        addLog("Connected " + device.getMac());
                        macs.add(mac);
                        notifyData(bleDevice);

                    }

                    @Override
                    public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
//                        Toast.makeText(MainActivity.this, "断开连接"+device.getName(), Toast.LENGTH_SHORT).show();
                        addLog("DisConnected " + device.getMac());
                    }
                });
            }

    }

    private void notifyData(BleDevice bleDevice){
        BleManager.getInstance().notify(bleDevice, SERVICE_UUID.toString(), NOTIFY_UUID.toString(), new BleNotifyCallback() {
            @Override
            public void onNotifySuccess() {
                addLog("onNotifySuccess " + bleDevice.getMac());
                write(bleDevice,"ATZ\\r\\n");
            }

            @Override
            public void onNotifyFailure(BleException exception) {
                addLog("onNotifyFailure " + bleDevice.getMac());
                Log.i(TAG, "onNotifyFailure: 失败"+bleDevice.getMac());
            }

            @Override
            public void onCharacteristicChanged(byte[] data) {
                addLog("获取数据 " + bleDevice.getMac() );
                String result = new String(data);
                addLog(result);
                if(new String(data).equals("OK")){
                    write(bleDevice,"ATLED\\r\\n");
                }
            }
        });
    }

    private void write(BleDevice bleDevice,String data){
        try {
            BleManager.getInstance().write(bleDevice, SERVICE_UUID.toString(), WRITE_UUID.toString(), data.getBytes("UTF-8"), new BleWriteCallback() {
                @Override
                public void onWriteSuccess(int current, int total, byte[] justWrite) {
                    addLog("onWriteSuccess " + bleDevice.getMac());
                    addLog(new String(justWrite));
                }

                @Override
                public void onWriteFailure(BleException exception) {
                    addLog("onWriteFailure " + bleDevice.getMac());
                }
            });
        } catch (UnsupportedEncodingException e) {
            addLog("写入异常“ " + bleDevice.getMac() + e.getLocalizedMessage());
            throw new RuntimeException(e);
        }
    }

    public void onStartConnect(View view) {
        checkPermissions();
    }



    @Override
    public final void onRequestPermissionsResult(int requestCode,
                                                 @NonNull String[] permissions,
                                                 @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_PERMISSION_LOCATION:
                if (grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                            onPermissionGranted(permissions[i]);
                        }
                    }
                }
                break;
        }
    }

    private void checkPermissions() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            Toast.makeText(this,"打开蓝牙", Toast.LENGTH_LONG).show();
            return;
        }

        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.BLUETOOTH_SCAN};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                onPermissionGranted(permission);
            } else {
                permissionDeniedList.add(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
        }
    }

    private void onPermissionGranted(String permission) {
        switch (permission) {
            case Manifest.permission.ACCESS_FINE_LOCATION:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
                    Toast.makeText(this, "请允许权限", Toast.LENGTH_SHORT).show();
                } else {
                    scanBleDevice();
                }
                break;
        }
    }

    private boolean checkGPSIsOpen() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null)
            return false;
        return locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_OPEN_GPS) {
            if (checkGPSIsOpen()) {
                scanBleDevice();
            }
        }
    }

    private void addLog(String log){
        Log.i(TAG, log);
        myTextView.setText(log+"\n"+ myTextView.getText());


    }
    private void clearLog(){
        myTextView.setText("");
    }

    @Override
    protected void onDestroy() {
        BleManager.getInstance().disconnectAllDevice();
        super.onDestroy();
    }
}